package com.qf.chat.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.chat.commons.exception.ServiceException;
import com.qf.chat.commons.r.Codes;
import com.qf.chat.commons.utils.UserUtils;
import com.qf.chat.dao.FriendRequestDao;
import com.qf.chat.entity.FriendRequest;
import com.qf.chat.entity.vo.FriendRequestVo;
import com.qf.chat.entity.vo.RequestHandlerVo;
import com.qf.chat.service.FriendRelationService;
import com.qf.chat.service.FriendRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 好友申请表(FriendRequest)表服务实现类
 *
 * @author makejava
 * @since 2024-01-12 10:46:26
 */
@Service("friendRequestService")
public class FriendRequestServiceImpl extends ServiceImpl<FriendRequestDao, FriendRequest> implements FriendRequestService {

    @Autowired
    private FriendRelationService friendRelationService;

    /**
     * 保存好友申请
     * @param entity
     * @return
     */
    @Override
    public boolean save(FriendRequest entity) {
        //设置申请人id
        entity.setFromId(UserUtils.getUid());

        //判断 当前用户 和 被申请者id 是否已经是好友了
        if (friendRelationService.isFriendRelation(entity.getFromId(), entity.getToId())) {
            throw new ServiceException(Codes.IS_FIRENDS);
        }

        //判断 当前用户 和 被申请者id 是否已经发送过好友申请了
        Long count = this.query()
                .eq("from_id", entity.getFromId())
                .eq("to_id", entity.getToId())
                .ne("status", 2)
                .count();

        if (count > 0) {
            throw new ServiceException(Codes.IS_REQUEST);
        }

        return super.save(entity);
    }

    /**
     * 查询所有发送给"我"的好友申请列表
     * @return
     */
    @Override
    public List<FriendRequestVo> queryMeRequest() {
        return getBaseMapper().queryMeRequest(UserUtils.getUid());
    }

    /**
     * 处理好友申请
     * @param requestHandlerVo
     * @return
     */
    @Override
    @Transactional
    public int requstHandler(RequestHandlerVo requestHandlerVo) {

        //改申请状态
        FriendRequest friendRequest = this.getById(requestHandlerVo.getId());
        if (friendRequest == null) {
            throw new ServiceException(Codes.DATA_ERROR);
        }

        //修改申请的状态
        this.update()
                .set("status", requestHandlerVo.getStatus())
                .set("update_time", new Date())
                .eq("id", requestHandlerVo.getId())
                .update();

        if (requestHandlerVo.getStatus() == 1) {
            //通过好友申请
            friendRelationService.addFriendRelation(
                    friendRequest.getFromId(),
                    friendRequest.getToId(),
                    friendRequest.getBeizhu(),
                    requestHandlerVo.getBeizhu());
        }

        return 1;
    }
}

